﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Super.Common.Security;
using Super.Common.Validate;
using Super.DomainService;
using Super.Entities;
using Super.Infrastructure;
using Super.Common;
using Super.Mvc;
using Super.Mvc.Form;

namespace Super.Web.Areas.Admin.Controllers
{
    public class ProductController : BaseController
    {
        //
        // GET: /Admin/Product/

        public ActionResult Index()
        {
            var adp = new DbContextAdapter();
            var productService = new ProductService(adp);
            var page = Query.Params("pageNum");
            var orderField = Query.Post("orderField");
            var orderDirection = Query.Post("orderDirection");


            if (string.IsNullOrEmpty(page))
            {
                page = "1";
            }
            var keyword = Query.Post("keyword");
            var Category = Query.Post("Category").ToInt(0);
            var startTime = Query.Post("startTime").ToDateTime();

            var where = PredicateBuilder.True<Product>();
            where = where.And(a => a.IsDel == false);

            if (!string.IsNullOrEmpty(keyword))
            {
                where = where.And(a => a.Title.Contains(keyword.Trim()) ||
                    a.Barcode.Contains(keyword.Trim()) ||
                    a.JianMa.Contains(keyword.Trim())
                    );

                ViewBag.keyword = keyword;
            }

            if (Category > 0)
            {
                where = where.And(a => a.Category_ID == Category);
            }

            if (startTime != null)
            {
                where = where.And(a => a.CreateTime > startTime);
                ViewBag.startTime = startTime;
            }

            var selector = new Func<Product, dynamic>(a => a.ID);

            ViewBag.orderDirection = "asc";//添加一个默认排序值
            if (!string.IsNullOrEmpty(orderField))
            {
                ViewBag.orderField = orderField;
                ViewBag.orderDirection = orderDirection;
                if (orderField == "cbprice")
                {
                    selector = a => a.CBPrice;
                }

                if (orderField == "lsprice")
                {
                    selector = a => a.LSPrice;
                }
                if (orderField == "createTime")
                {
                    selector = a => a.CreateTime;
                }

            }

            var produtsEnu = productService.Repository.Find(where).OrderByDescending(selector);
            if (orderDirection == "desc")
            {
                produtsEnu = productService.Repository.Find(where).OrderByDescending(selector);
            }
            if (orderDirection == "asc")
            {
                produtsEnu = productService.Repository.Find(where).OrderBy(selector);
            }

            var produts = produtsEnu.Page(page.ToInt(1), PageSize);
            BindPage(produts.ItemCount, page.ToInt(), PageSize);

            ViewBag.Records = produts.ItemCount;

            GetCategory(Category);

            return View(produts.ItemCollection.ToList());
        }

        /// <summary>
        /// 产品入库
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit()
        {
            GetCategory(null);
            GetSupplier(null);
            var pid = Query.Get("pid").ToInt(0);
            var interfaceIds = "";
            var interfaceNames = "";
            if (pid > 0)
            {
                var adp = new DbContextAdapter();
                var productService = new ProductService(adp);
                var productModel = productService.Repository.Find(a => a.ID == pid).FirstOrDefault();
                if (productModel != null && productModel.ProductInterfaceType.Count > 0)
                {
                    foreach (var interfaceType in productModel.ProductInterfaceType)
                    {
                        interfaceIds = interfaceIds + "," + interfaceType.InterfaceType_ID;
                        if (string.IsNullOrEmpty(interfaceNames))
                        {
                            interfaceNames = interfaceType.InterfaceType.Model;

                        }
                        else
                        {
                            interfaceNames = interfaceNames + "," + interfaceType.InterfaceType.Model;
                        }
                    }
                }
                ViewBag.interfaceIds = interfaceIds;
                ViewBag.interfaceNames = interfaceNames;
                return View(productModel);
            }
            ViewBag.interfaceIds = interfaceIds;
            ViewBag.interfaceNames = interfaceNames;
            return View();
        }

        [HttpPost]
        public JsonResult Edit([Bind(Prefix = "")]Product model)
        {

            if (model == null) throw new ArgumentNullException("model");
            var adp = new DbContextAdapter();
            var productService = new ProductService(adp);
            var productInterfaceTypeService = new ProductInterfaceTypeService(adp);
            if (string.IsNullOrEmpty(model.Barcode))
            {
                model.Barcode = Number.GetRandomNumber(8).ToString();
            }
            if(model.Category_ID==null)
            {
                return JsonBack.Tip("请选择分类！");
                
            }
            var interfaceIds = Query.Post("interface.ID");
            var ids = interfaceIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.ToInt());

            var productInterfaceTypeList = productInterfaceTypeService.Repository.Find(a => a.Product_ID == model.ID);//已有分类


            foreach (var productInterfaceType in productInterfaceTypeList)
            {
                productInterfaceTypeService.Repository.Delete(productInterfaceType, true);
            }

            foreach (var id in ids)
            {
                var productInterfaceTypeModel = new ProductInterfaceType();
                productInterfaceTypeModel.Product_ID = model.ID;
                productInterfaceTypeModel.InterfaceType_ID = id;
                productInterfaceTypeService.Repository.InsertOrUpdate(productInterfaceTypeModel);
            }
            if (model.ID <= 0)
            {
                model.CreateTime = DateTime.Now;
            }


            if (string.IsNullOrEmpty(model.JianMa))
            {
                var dicService = new DicService(adp);
                model.JianMa = dicService.GetChineseFirstSpell(model.Title);
            }

            productService.Repository.InsertOrUpdate(model);
            adp.SaveChanges();
            return JsonBack.Tip(adp.ErrorMessage, "productIndex");
        }

        public JsonResult Delete()
        {
            var id = Query.Get("pid").ToInt(0);
            var adp = new DbContextAdapter();
            var productService = new ProductService(adp);
            var productModel = productService.Repository.Find(a => a.ID == id).FirstOrDefault();
            if (productModel != null)
            {
                productService.Repository.Delete(productModel);
            }
            adp.SaveChanges();
            return JsonBack.Tip(adp.ErrorMessage, "productIndex");
        }



        public ActionResult SubSearch()
        {
            var page = Query.Params("pageNum");
            if (string.IsNullOrEmpty(page))
            {
                page = "1";
            }
            var where = PredicateBuilder.True<Product>();
            where = where.And(a => a.IsDel == false);
            var keyword = Query.Post("keyword");
            if (!string.IsNullOrEmpty(keyword))
            {
                where = where.And(a => a.Title.Contains(keyword.Trim()) ||
                    a.Barcode.Contains(keyword.Trim()) ||
                    a.JianMa.Contains(keyword.Trim())
                    );

                ViewBag.keyword = keyword;
            }
            var adp = new DbContextAdapter();
            var productService = new ProductService(adp);
            var productList =
                productService.Repository.Find(where).Page(page.ToInt(1), PageSize);
            BindPage(productList.ItemCount, page.ToInt(), PageSize);

            ViewBag.Records = productList.ItemCount;
            return View(productList.ItemCollection.ToList());
        }


    }
}
